package cn.buglife.concurrent.barrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier 类是一种同步机制，它能够对处理一些算法的线程实现同步。
 * 换句话讲，它就是一个所有线程必须等待的一个栅栏，直到所有线程都到达这里， 然后所有线程才可以继续做其他事情。
 *
 * @author zhangjun
 */
public class CyclicBarrierSample {

  public static void main(String[] args) {
    // 在创建一个 CyclicBarrier 的时候你需要定义有多少线程在被释放之前等待栅栏
    int threadWaitCount = 2;

    Runnable barrier1Action = () -> System.out.println("BarrierAction 1 executed ");
    Runnable barrier2Action = () -> System.out.println("BarrierAction 2 executed ");

    CyclicBarrier barrier1 = new CyclicBarrier(threadWaitCount, barrier1Action);
    CyclicBarrier barrier2 = new CyclicBarrier(threadWaitCount, barrier2Action);

    Runnable barrierThread = () -> {
      try {
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + " waiting at barrier 1");
        barrier1.await();

        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + " waiting at barrier 2");
        barrier2.await();
        System.out.println(Thread.currentThread().getName() + " done!");
      } catch (InterruptedException | BrokenBarrierException e) {
        e.printStackTrace();
      }

    };

    new Thread(barrierThread).start();
    new Thread(barrierThread).start();

  }
}
